package com.dk.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class JavaMailUtil {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;


    public String test(String title,String text,String address) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

        try {
            messageHelper.setSubject(title);
            messageHelper.setText(text, true); //true :是否解析 html代码
            //收件人
            messageHelper.setTo(address);
            //发件人
            messageHelper.setFrom(from);
            javaMailSender.send(message);
            return "ok";
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }
    }
}
